package com.csgc.camera.biz.other.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import coil.load

import com.csgc.camera.base.BaseBindingActivity
import com.csgc.camera.bean.UserInfo
import com.csgc.camera.bean.UserInfoParams
import com.csgc.camera.bean.WxBindParams
import com.csgc.camera.biz.other.BindPhoneActivity

import com.csgc.camera.events.BindPhoneEvents
import com.csgc.camera.events.LogoutEvents
import com.csgc.camera.events.WXAuthCodeBindEvents
import com.csgc.camera.http.doFailure
import com.csgc.camera.http.doSuccess
import com.csgc.camera.http.viewmodel.AppViewModel
import com.csgc.camera.storage.CommonPreference
import com.csgc.camera.storage.SettingPreference
import com.csgc.camera.storage.UserPreference
import com.csgc.camera.util.AppUtil
import com.csgc.camera.util.WXWrapper
import com.csgc.camera.util.clickWithTrigger
import com.csgc.camera.widget.dialog.CommonHandleTipsDialog
import com.cysd.spsyxj.R
import com.cysd.spsyxj.databinding.ActivityAccountSettingBinding

import com.drake.channel.receiveEvent
import com.drake.channel.sendEvent
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.ToastUtils
import com.hlyj.http.base.tool.lib_hlyj_base.Constants
import com.hlyj.http.base.tool.lib_hlyj_base.camera.LoginResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.utils.MMKVUtils
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi

class AccountSettingActivity:BaseBindingActivity<ActivityAccountSettingBinding>(ActivityAccountSettingBinding::inflate) {

    companion object{
        fun launch(context:Context){
            context.startActivity(Intent(context,AccountSettingActivity::class.java))
        }
    }
    private val viewModel:AppViewModel by viewModels()
    var userInfo: LoginResultBean?=null


    private val logoutDialog:CommonHandleTipsDialog by lazy {
        val dialog = CommonHandleTipsDialog(this,"退出账号", content = "是否退出当前账号", leftTxt = "取消", rightTxt = "确定")
        dialog.listener = object :CommonHandleTipsDialog.DialogActionListener{
            override fun sure(type: String) {
                //清楚缓存info
                MMKVUtils.removeObject(Constants.LoginResultBean)
                //LOGOmask
                SettingPreference.instance.setLogoWaterMark(true)
                //发送 events
                sendEvent(LogoutEvents(true))
                finish()
            }
        }
        dialog
    }

    private val cleanUserDialog:CommonHandleTipsDialog by lazy {
        val dialog = CommonHandleTipsDialog(this,"账户注销", content = "以下信息将被清空且无法找回", leftTxt = "确认注销", rightTxt = "取消")
        dialog.listener = object :CommonHandleTipsDialog.DialogActionListener{
            override fun sure(type: String) {
                ToastUtils.show("注销完成")
                //清除缓存info
                 MMKVUtils.removeObject(Constants.LoginResultBean)
                //发送 events
                sendEvent(LogoutEvents(true))
                finish()
                //请求接口
              //  viewModel.cleanUserInfo(UserInfoParams(token = UserPreference.instance.getUserToken()))

            }
        }
        dialog
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        immersionBar {
            fitsSystemWindows(true)
            //白色状态栏，黑色字体
            statusBarColor(R.color.white)
            statusBarDarkFont(true)

        }
        userInfo= MMKVUtils.getObject(com.hlyj.http.base.tool.lib_hlyj_base.Constants.LoginResultBean,LoginResultBean::class.java)
        initListener()
        initData()

        viewModel.cleanInfoResult.observe(this){result->
            result.doSuccess {
                ToastUtils.show("注销完成")
                //清除缓存info
                UserPreference.instance.cleanUserInfo()
                MMKVUtils.removeObject(Constants.LoginResultBean)
                //发送 events
                sendEvent(LogoutEvents(true))
                finish()
            }
            result.doFailure {
                ToastUtils.show("注销失败")
            }

        }
    }


    private fun initData(){



            if (userInfo!=null){
                binding.tvUserName.text = phoneHide(userInfo?.phone?:"")
            }else{
                binding.tvUserName.text = "游客用户"
            }


            userInfo?.let {

                if (!it.phone.isNullOrEmpty()){
                    binding.tvPhoneBind.text = phoneHide(userInfo?.phone?:"")
                }else{
                    binding.tvPhoneBind.text = "未登录"
                }

                if(!it.nickname.isNullOrEmpty()){
                    binding.tvWxBind.text = it.nickname
                }else{
                    binding.tvWxBind.text = "未绑定"
                }

            }





    }

    private fun initListener(){



        binding.ivBack.clickWithTrigger { finish() }
        binding.layoutCancelUser.clickWithTrigger {
            cleanUserDialog.showDialog()
        }
        binding.tvLogoutUser.clickWithTrigger {
            logoutDialog.showDialog()
        }

        binding.layoutBindPhone.clickWithTrigger {
            if (userInfo?.phone.isNullOrEmpty()){
                BindPhoneActivity.launch(this)
            }
        }

        binding.layoutBindWx.clickWithTrigger {
//            if (userInfo?.nickname.isNullOrEmpty()){
//                WXWrapper.instance.bind()
//            }

        }

        receiveEvent<WXAuthCodeBindEvents> {
            //绑定微信
            viewModel.bindWx(WxBindParams(it.code,UserPreference.instance.getOaid(),UserPreference.instance.getUserToken(),packageName, AppUtil.getChannel()))
        }
        receiveEvent<BindPhoneEvents> {
            //手机号绑定完成
            initData()
        }


//        viewModel.bindWxResult.observe(this){result->
//
//            result.doSuccess {baseResponse ->
//                baseResponse.data?.let {
//                    //更新userInfo
////                    userInfo?.userName = it.userName
////                    userInfo?.userPhoto = it.userPhoto
////                    userInfo?.vipType = it.vipType
////                    userInfo?.vipTime = it.vipTime
//
//                    UserPreference.instance.setUserInfo(userAdapter.toJson(it))
//                    binding.ivUserPhoto.load(it.userPhoto)
//                    binding.tvWxBind.text = it.userName
//
//                }
//
//            }
//
//
//        }

    }


    private fun phoneHide(phone: String): String {
        val sb = StringBuilder()
        if (!TextUtils.isEmpty(phone) && phone.length > 6) {
            for (i in phone.indices) {
                val c = phone[i]
                if (i in 3..6) {
                    sb.append('*')
                } else {
                    sb.append(c)
                }
            }
        }
        return sb.toString()
    }

}